package utils.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URL;

/**
 * This class read a URL (a file uri in this case) and return a JScrollPane that
 * displays the file content.
 * 
 * @author j55wu
 * 
 */
public class FileLoader {

	// private static boolean windows;
	//
	// public FileLoader(boolean platformIsWindows){
	// windows = platformIsWindows;
	// }

	public static URL getRelativePath(String given, boolean windowsPlatform) {
		File file = new File(given);
		String abs = file.getAbsolutePath();
		if (windowsPlatform) {
			abs = abs.substring(0, abs.lastIndexOf("\\")) + "\\" + given;
		} else {
			abs = "file:" + abs.substring(0, abs.lastIndexOf("/")) + "/"
					+ given;
		}
		URL ret = null;
		try {
			ret = new URI(abs).toURL();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static void writeAsFile(String s, String fn, String linebreak) {
		Writer out = null;
		try {
			OutputStream os = new FileOutputStream(new File(fn));
			out = new OutputStreamWriter(os, "UTF8");
			String[] ss = s.split(linebreak);
			for (String line : ss) {
				out.write(line);
				out.write("\n");
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void writeAsFile(String s, String fn) {
		Writer out = null;
		try {
			OutputStream os = new FileOutputStream(new File(fn));
			out = new OutputStreamWriter(os, "UTF8");
			out.write(s);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
